/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class UserModel {

  Connection connection;

  public UserModel(Connection connection) {
    this.connection = connection;
  }

  public ResultSet getUsername(String username) throws SQLException {
    String query = "SELECT username,ID FROM user WHERE username='" + username + "'";
    Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    ResultSet rs = statement.executeQuery(query);
    return rs;
  }

  public ResultSet getEmail(String email) throws SQLException {
    String query = "SELECT email FROM user WHERE email='" + email + "'";
    Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    ResultSet rs = statement.executeQuery(query);
    return rs;
  }

  public ResultSet getUserInfo(String userid) throws SQLException {
    String query = "SELECT username, full_name, email, gender, birth, avatar, about_me, post_count, comment_count"
            + " FROM user"
            + " WHERE ID='"
            + userid
            + "'"
            + " LIMIT 1";
    //System.out.print(query);
    Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    ResultSet rs = statement.executeQuery(query);
    return rs;
  }

  public void incCommentCount(String userid) throws SQLException {
    String query = "UPDATE user SET comment_count=comment_count+1 WHERE ID=" + userid;
    Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    statement.executeUpdate(query);
  }

  public void decCommentCount(String userid) throws SQLException {
    String query = "UPDATE user SET comment_count=comment_count-1 WHERE ID=" + userid;
    Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    statement.executeUpdate(query);
  }

  public void incUserPostCount(String userid) throws SQLException {
    String query = "UPDATE user SET post_count=post_count+1 WHERE ID=" + userid;
    Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    statement.executeUpdate(query);
  }
  
  public void updateUserInfo(String userid, String avatar, String email, String about_me) throws SQLException {
    String query = "UPDATE user SET email='"+email+"', avatar='"+avatar+"', about_me='"+about_me+"' WHERE ID='"+userid+"'";
    Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    statement.executeUpdate(query);
  }
}
